<template>
  <el-dialog @open="assign" :title="title" width="45%">
    <el-form ref="form" :model="values" :rules="rules" status-icon>
      <div style="margin: 0.5rem">🐳</div>
      <el-form-item prop="username">
        <el-input
          v-model="values.username"
          placeholder="用户名"
          autocomplete="off"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="values.password"
          placeholder="密码"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="values.superuser" placeholder="管理员等级">
          <el-option
            v-for="(value, key) in superuser"
            :value="key"
            :label="value"
            :key="key"
            >{{ value }}</el-option
          >
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('update:model-value', false)">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { toRefs, ref, reactive } from "vue";

export default {
  emits: ["success"],
  props: {
    title: String,
    initValues: Object,
  },

  setup(props, { emit }) {
    const { title, initValues } = toRefs(props);
    const superuser = {
        0: "普通管理员",
        1: "超级管理员",
      },
      rules = {
        username: [
          {
            required: true,
            message: "请输入用户名",
            trigger: "blur",
          },
          {
            min: 2,
            max: 20,
            message: "用户名在2到20个字符之间",
            trigger: "blur",
          },
        ],
        password: [
          {
            min: 6,
            message: "密码最少为6个字符",
            trigger: "blur",
          },
        ],
        superuser: [
          {
            required: true,
            message: "请选择该管理员的等级",
            trigger: "blur",
          },
        ],
      };
    const form = ref(null),
      values = reactive({
        username: "",
        password: "",
        superuser: "",
      });
    const submit = async () => {
      try {
        await form.value.validate();
        emit("success", values);
      } catch (e) {
        //
      }
    };
    //初始化赋值，在对话框打开时执行
    const assign = () => {
      Object.assign(values, initValues.value);
    };
    return {
      values,
      rules,
      form,
      superuser,
      emit,
      submit,
      assign,
      // eslint-disable-next-line vue/no-dupe-keys
      title,
      // eslint-disable-next-line vue/no-dupe-keys
      initValues,
    };
  },
};
</script>
<style>
@media screen and (max-width: 600px) {
  .el-dialog {
    margin: 0px;
    width: 100%;
  }
  .cell .el-button--danger {
    margin-left: 0px;
  }
}
</style>
